package com.asset.dispoal.address.service.commom;

import com.asset.dispoal.address.domain.db.entity.SysAddressDo;
import com.asset.dispoal.address.domain.db.mapper.SysAddressMapper;
import com.asset.dispoal.address.dto.SysAddressRequest;
import com.asset.dispoal.address.dto.SysAddressResponse;
import com.asset.dispoal.address.service.converter.AddressConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import tech.mhuang.pacebox.core.ddd.BaseCommand;
import tech.mhuang.pacebox.core.util.StringUtil;
import tech.mhuang.pacebox.springboot.core.local.GlobalHeaderThreadLocal;
import tech.mhuang.pacebox.springboot.protocol.Result;

import java.util.List;
import java.util.stream.Collectors;


/**
 * @author qr
 * @date 2022/2/16$
 */
@Component
public class AddressQueryAllCommand implements BaseCommand<SysAddressRequest, Result<List<SysAddressResponse>>> {

    @Autowired
    SysAddressMapper sysAddressMapper;

    @Override
    public Result<List<SysAddressResponse>> execute(SysAddressRequest request) {
        final SysAddressDo sysAddressDo = AddressConverter.INSTANCE.reqToDo(request);
        sysAddressDo.setPermission((String) GlobalHeaderThreadLocal.getOrException().getExtraMap().get("permission"));
        final List<SysAddressDo> sysAddressDos = sysAddressMapper.queryList(sysAddressDo);
        List<SysAddressResponse> sysAddressResponses = AddressConverter.INSTANCE.dosToRes(sysAddressDos);
        List<SysAddressResponse> collect = sysAddressResponses.stream().filter(item -> StringUtil.isBlank(item.getCityCode())).collect(Collectors.toList());
        sysAddressResponses.removeAll(collect);
        final List<SysAddressResponse> recursion = this.recursion(sysAddressResponses, collect);
        return Result.ok(recursion);
    }


    private List<SysAddressResponse> recursion(List<SysAddressResponse> sysAddressResponses, List<SysAddressResponse> collect) {
        for (SysAddressResponse response : collect) {
            final List<SysAddressResponse> sysAddressResponseList = sysAddressResponses.stream().filter(itme -> itme.getParentCode().equals(response.getCode())).collect(Collectors.toList());
            response.setResponseList(sysAddressResponseList);
            recursion(sysAddressResponses, sysAddressResponseList);
        }
        return collect;
    }

}
